#!/usr/bin/perl
#
# Enter population figures from an UN table into the counter records
#
use Counter;
use Fcntl;

$write = 1;

# special mapping for some names
%namemap = 
(
 "Brunei Darussalam" => "BN",
 "Central African Rep." => "CF",
 "China f"              => "CN",
 "Dem. Rep. of the Congo" => "CD",
 "Iran (Islamic Rep. of)" => "IR",
 "Korea, Dem. People's Rep." => "KP",
 "Korea, Republic of" => "KR",
 "Lao People's Dem. Rep." => "LA",
 "Libyan Arab Jamahiriya" => "LY",
 "Micronesia, Fed. States of" => "FM",
 "Netherlands" => "NL",
 "Occpd. Palestinian Terr. j" => "PS",
 "Republic of Moldova" => "MD",
 "Russian Federation" => "RU",
 "Saint Vincent/Grenadines" => "VC",
 "Syrian Arab Republic" => "SY",
 "The FYR of Macedonia" => "MK",
 "Tonga" => "TO",
 "United Kingdom" => "GB",
 "United Rep. of Tanzania" => "TZ",
 "U.S. Virgin Islands" => "VI",
 "Viet Nam" => "VN",
 "Yugoslavia" => "YU",
 );

$places = Counter::openfile("places");

while (<>) {
    next if /^ /;
    if (/^\s?(\S+( \S+)*)\s+(\d+)( \S)*\s+(\d+)/) {
	$name = $1;
	$males = $3;
	$females = $5;
	#print "$name: $males males, $females females\n";
	@rec = $places->select("longname = ? and type = 'country'", $name);
	if (@rec == 0 && $namemap{$name}) {
	    @rec = $places->select("name = ? and type = 'country'", $namemap{$name});
	}
	if (@rec > 0) {
	    $prevpop = $rec[0]->{population}; 
            $code = $rec[0]->{name};
	    $newpop = ($males + $females) / 1000;
	    if ($prevpop == 0) {
		print "$code $name had no previous population\n";
	    } else {
		printf "$code $name: Prev pop $prevpop, new $newpop change %4.2f\n",
		($newpop - $prevpop) * 100 / $prevpop;
	    }
	    if ($write) {
		$rec[0]->{population} = $newpop;
		$rec[0]->store();
	    }
	} else {
	    print "name $name not found in DB\n";
	}
    }
}
